﻿using System.Collections.Generic;
using System.Linq;
using ControleRepresentanteSync.ControleRepresentanteServices;

namespace ControleRepresentanteSync.Application.Pedido
{
    internal class AttributeListPresenter : PresenterBase<IAttributeListViewModel>
    {
        public AttributeListPresenter(IAttributeListViewModel attributeListViewModel, IEnumerable<AttributeContract> attributes, IViewModelFactory viewModelFactory)
            : base(attributeListViewModel)
        {
            foreach (AttributeContract attributeContract in attributes)
            {
                IAttributeItem attributeItem = viewModelFactory.CreateViewModel<IAttributeItem>();
                new AttributeItemPresenter(attributeItem, attributeContract);
                ViewModel.Attributes.Add(attributeItem);
            }

            ViewModel.GetAttributeValuesRequested += ViewModelGetAttributeValuesRequested;
        }

        private void ViewModelGetAttributeValuesRequested(object sender, AttributeValuesEventArgs e)
        {
            e.AttributeValues = ViewModel.Attributes
                .Select(attributeItem => new AttributeValueContract
                {
                    AttributeId = attributeItem.Contract.Id,
                    Value = attributeItem.Value
                })
                .ToArray();
        }

        public override void Dispose()
        {
            base.Dispose();

            foreach (IAttributeItem attributeItem in ViewModel.Attributes)
            {
                attributeItem.FireOnClose();
            }

            ViewModel.GetAttributeValuesRequested -= ViewModelGetAttributeValuesRequested;
        }
    }
}